package model.jena.model;

import govenor.status.FileStored;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import model.jena.properties.FileItem;
import model.jena.properties.FileStore;
import networkdescriptor.NetworkDescriptor;

import com.hp.hpl.jena.rdf.model.Bag;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.rdf.model.SimpleSelector;
import com.hp.hpl.jena.rdf.model.Statement;
import com.hp.hpl.jena.rdf.model.StmtIterator;

public class GovenorModelBuilder {
	public static Model buildModel(Map<String,FileStored> fileAndHostMap){
		Model model = ModelFactory.createDefaultModel();
		Set setOfEntries = fileAndHostMap.keySet();
		Iterator iter = setOfEntries.iterator() ;
		while(iter.hasNext()){
			String filename = (String)iter.next() ;
			Resource fileStatusResource = model.createResource("http://csi.ucd.ie/auto/FileItem/"+filename);
			NetworkDescriptor[] hostsOfFiles = fileAndHostMap.get(filename).getDownloadHosts();
			//The array is sorted, the first element is the quickest
			fileStatusResource.addProperty(FileItem.FILENAME,filename);
			fileStatusResource.addProperty(FileItem.PRIMARY_DOWNLOAD_HOSTNAME, hostsOfFiles[0].getHostname());
			fileStatusResource.addProperty(FileItem.PRIMARY_DOWNLOAD_PORT,""+hostsOfFiles[0].getPortNumber());
			if(hostsOfFiles.length > 1){
				fileStatusResource.addProperty(FileItem.SECONDARY_DOWNLOAD_HOSTNAME,hostsOfFiles[1].getHostname());
				fileStatusResource.addProperty(FileItem.SECONDARY_DOWNLOAD_PORT,""+hostsOfFiles[1].getPortNumber());
			}
		}
		Bag bagOfFiles = model.createBag();
		
		StmtIterator simpleIter = model.listStatements(new SimpleSelector(null,FileStore.FILENAME,(RDFNode)null){

			@Override
			public boolean selects(Statement s) {
				return super.selects(s);
			}
		});
        while (simpleIter.hasNext()) {
        	bagOfFiles.add( simpleIter.nextStatement().getSubject());
        }
        System.out.println("DEBUG");
        model.write(System.out);
		return model;
	}
}
